package com.zd.zuul.filter;

import com.alibaba.fastjson.JSON;

import com.netflix.zuul.context.RequestContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import utils.JwtSecret;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: sporadic
 * @description:
 * @author: LHD   QQ:1727865856
 * @create: 2019-11-16 12:11
 **/
@Component
public class ZuulFilter extends com.netflix.zuul.ZuulFilter {
    @Override
    public String filterType() {
        //在请求路由签被执行
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() {
        //获取当前请求上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取当前请求
        HttpServletRequest request = currentContext.getRequest();
        //判断是否是登录
        if(request.getRequestURI().indexOf("login")!=-1||request.getRequestURI().indexOf("userInfo")!=-1){
            return null;
        }else {
            //获取头部信息，「我们将头信息放入header中」
            String token = request.getHeader("token").trim();

            if (token == null || token == "") {
                //设置响应字符集
                currentContext.getResponse().addHeader("Content-Type", "application/json;charset=UTF-8");
                // 没有token，登录校验失败，拦截
                currentContext.setSendZuulResponse(false);
                Map<String,Object> respones=new HashMap<>();
                respones.put("code",HttpStatus.UNAUTHORIZED.value());
                respones.put("msg","请求被拦截");
                currentContext.setResponseBody(JSON.toJSONString(respones));
                // 返回401状态码。也可以考虑重定向到登录页。
                currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }else{
                if(JwtSecret.vladateToken(token)==""){
                    //设置响应字符集
                    currentContext.getResponse().addHeader("Content-Type", "application/json;charset=UTF-8");
                    // 没有token，登录校验失败，拦截
                    currentContext.setSendZuulResponse(false);
                    Map<String,Object> respones=new HashMap<>();
                    respones.put("code",HttpStatus.UNAUTHORIZED.value());
                    respones.put("msg","无效的token");
                    currentContext.setResponseBody(JSON.toJSONString(respones));
                    // 返回401状态码。也可以考虑重定向到登录页。
                    currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                }
            }
        }
        return null;
    }
}
